package com.hntx.joymusic.web;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;

import com.blankj.utilcode.utils.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hntx.joymusic.Constants;
import com.hntx.joymusic.MyApp;
import com.hntx.joymusic.R;
import com.hntx.joymusic.bean.SocketBean;
import com.hntx.joymusic.bean.VideoBean;
import com.hntx.joymusic.bus.RxBus;
import com.hntx.joymusic.lsplayer.LsPlayerActivity;
import com.hntx.joymusic.service.MPushService;
import com.hntx.joymusic.util.DeletePkgUtils;
import com.hntx.joymusic.util.LiveDataBus;
import com.hntx.joymusic.util.PlayUtils;
import com.hntx.joymusic.util.SetNetWorkUtils;
import com.hntx.joymusic.util.ThreadPoolManager;
import com.hntx.joymusic.util.VersionInfoUtils;
import com.hntx.joymusic.webscoket.WebScoketClient;
import com.hntx.joymusic.yun.YunUtils;

import org.java_websocket.client.WebSocketClient;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends AppCompatActivity implements
        WebScoketClient.WebScoketConnectListener {
    static final int MSG_EXIT_DELAY = 5;
    static final int MSG_LOAD_HOME_URL = 4;
    static final int MSG_PAYRESULT_WEB = 6;
    static final int MSG_INIT = 1;
    static final int MSG_TO_PLAY_ACTIVITY = 2;
    private String TAG = "MainActivity";
    private WebView contentWebView;
    private boolean isExit;
    private ArrayList<VideoBean> videoBeanList = new ArrayList<>();
    private int startPosition, popStartPos = 0;
    private String firstUrl = null;
    private final int PLAY_AC_CODE = 10000, PLAY_AC_RESULT_CODE = 10001;
    private int currentVersion = 0;
    /**
     * 2020.6.8 添加外部参数获取
     */
    private Map<String, String> externalParamsMap;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message message) {
            switch (message.what) {
                case MSG_EXIT_DELAY:
                    isExit = false;
                case MSG_INIT:
                    initMain();
                    break;
                case MSG_LOAD_HOME_URL:
                    progress_img.setVisibility(View.VISIBLE);
                    contentWebView.loadUrl(Constants.HOME_URL);
                    break;
                case MSG_TO_PLAY_ACTIVITY:
                    if (pay_img_top.getVisibility() == View.VISIBLE) {
                        pay_img_top.setVisibility(View.GONE);
                    }
                    Intent intent = new Intent();
                    intent.putParcelableArrayListExtra("video_bean_list", videoBeanList);
                    intent.putExtra("start_position", startPosition);
                    intent.putExtra("userId", userMac);
                    if (!TextUtils.isEmpty(firstUrl)) {
                        intent.putExtra("firstUrl", firstUrl);
                    }
                    intent.setClass(MainActivity.this, LsPlayerActivity.class);
                    startActivity(intent);
                    break;
                case MSG_PAYRESULT_WEB:
                    contentWebView.loadUrl(message.obj.toString());
                    break;
                default:
                    break;
            }
            super.handleMessage(message);
        }
    };

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.activity_main);
        MyApp.getInstance().addActivity(this);
        yunInfo();
        initView();
//        copyMusic();
        getUserInfo();
//        startService();
        WebSocketConnect();
        initBus();
        LiveDataBus.getInstance().with("webSLogin").setValue(true);
        handler.sendEmptyMessage(MSG_INIT);
    }

//    private void copyMusic() {
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                copyFile();
//            }
//        }).start();
//    }

//    private void copyFile() {
//        InputStream in = null;
//        FileOutputStream out = null;
//        String path = "/sdcard/7000948.ts"; // data/data目录
//        File file = new File(path);
//        if (!file.exists()) {
//            try {
//                file.createNewFile();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        } else {
//            return;
//        }
//        try {
//            in = getAssets().open("7000948.ts");
//            out = new FileOutputStream(file);
//            int length = -1;
//            byte[] buf = new byte[1024];
//            while ((length = in.read(buf)) != -1) {
//                out.write(buf, 0, length);
//            }
//            out.flush();
//        } catch (FileNotFoundException e1) {
//            e1.printStackTrace();
//        } catch (IOException e1) {
//            e1.printStackTrace();
//        } finally {
//            if (in != null) {
//                try {
//                    in.close();
//                } catch (IOException e1) {
//                    e1.printStackTrace();
//                }
//            }
//            if (out != null) {
//                try {
//                    out.close();
//                } catch (IOException e1) {
//                    e1.printStackTrace();
//                }
//            }
//            ToastUtils.showShortToastSafe("文件下载完成！" + file.getPath());
//        }
//    }

    private void yunInfo() {
        YunUtils.yunInit(bean -> {
            String fileId = bean.getFileId();
            if (!TextUtils.isEmpty(fileId))
                Constants.uploadFileId = bean.getFileId();
        });
    }

    WebScoketClient webSocketClient;

    private void WebSocketConnect() {
        LiveDataBus.getInstance().with("webSLogin", Boolean.class)
                .observe(this, o -> {
                    if (o) {
                        ThreadPoolManager.getInstance().execute(() -> {
                            if (webSocketClient == null) {
                                Log.d(TAG, "开始登陆");
                                javaWebsocketConnect();
                            } else {
                                javaWebsocketReconect();
                            }
                        });
                    }
                });
    }

    String userMac;

    public void javaWebsocketConnect() {
        if (TextUtils.isEmpty(userMac)) return;
        webSocketClient = WebScoketClient.getWebScoketClient();
        webSocketClient.javaWebSocketConnect(userMac);
        webSocketClient.addWebScoketConnectListener(this);
    }

    public void javaWebsocketReconect() {
        try {
            webSocketClient.javaWebSocketReconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void startService() {
        Intent intentService = new Intent(this, MPushService.class);
        startService(intentService);
    }

    private final CompositeDisposable disposables = new CompositeDisposable();

    private void initBus() {
        LiveDataBus.getInstance().with("main", Integer.class).observe(this, code -> {
            if (code == PLAY_AC_RESULT_CODE)
                contentWebView.loadUrl("javascript:playBack()");
        });

//        LiveDataBus.getInstance().with("socketmsg").observe(this, bean -> {
//            Log.d("服务器消息：", "shou页面：" + ((SocketBean) bean).getAction());
//            if ("order".equals(((SocketBean) bean).getAction())) {
//                dstartPlay(0, ((SocketBean) bean).getContent());
//            }
//        });
        disposables.add(RxBus.getInstance()
                .toObservable()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object -> {
                    Log.d("服务器消息：", "shou页面：" + ((SocketBean) object).getAction());
                    if ("order".equals(((SocketBean) object).getAction())) {
                        dstartPlay(0, ((SocketBean) object).getContent());
                    }
                }));
    }

    private void dstartPlay(int position, ArrayList<VideoBean> contentBeans) {
        StringBuilder sb = new StringBuilder();
        sb.append("__position=" + position);
        sb.append("__urlArray=" + contentBeans.toString());
        Log.d("playtest", sb.toString());
        startPosition = position;
        videoBeanList = contentBeans;
        if (videoBeanList.size() > 0 && videoBeanList.size() > startPosition) {
            firstUrl = videoBeanList.get(startPosition).getSongRes();
//                if (isCharge) {
//                    NewAuth(videoBeanList.get(startPosition).getSongId());
//                } else
            handler.sendEmptyMessage(MSG_TO_PLAY_ACTIVITY);
        }
    }

    private void initMain() {
        /**2020.3.5 添加二级跳转参数*/
        currentVersion = VersionInfoUtils.getVersionCode(this);
        externalParamsMap.put("versionCode", currentVersion + "");
        externalParamsMap.put("versionName", VersionInfoUtils.getAPKVersion(this));
        initParams(getIntent());
        //不允许检测升级
//        upgradeApk();
    }

    private void initParams(Intent intent) {
        if (intent != null) {
            Log.d(TAG, intent.getStringExtra("detcode") + "");
            Log.d(TAG, intent.getDataString() + "");
            Log.d(TAG, intent.toString() + "");
            Bundle bundle = intent.getExtras();
            if ((bundle != null) && (bundle.keySet().size() > 0)) {
                Iterator iterator = bundle.keySet().iterator();
                while (iterator.hasNext()) {
                    String str = (String) iterator.next();
                    externalParamsMap.put(str, bundle.get(str).toString());
                    Log.d(TAG, "key=" + str + "____value=" + bundle.get(str));
                }
            }
        }
    }

    private ImageView progress_img, pay_img_top;

    @SuppressLint("ResourceType")
    private void initView() {
        progress_img = findViewById(R.id.progress_img);
        pay_img_top = findViewById(R.id.pay_img_top);
        contentWebView = findViewById(R.id.webview);
        contentWebView.setBackgroundColor(getResources().getColor(R.color.trans));
        WebSettings settings = contentWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        contentWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView webView, String url, Bitmap bitmap) {
                super.onPageStarted(webView, url, bitmap);
            }

            @Override
            public void onPageFinished(final WebView webView, String url) {
                super.onPageFinished(webView, url);
                runOnUiThread(()->progress_img.setVisibility(View.GONE));
                if (isSimple) {
                    if (url.contains("list.html") && webView.getProgress() == 100) {
                        String js = "javascript:document.getElementById('pay').click()";
                        webView.postDelayed(() -> {
                            KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_LEFT);
                            final KeyEvent events = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER);
                            dispatchKeyEvent(event);
                            final Timer timer = new Timer();
                            timer.schedule(new TimerTask() {
                                @Override
                                public void run() {
                                    dispatchKeyEvent(events);
                                    timer.cancel();
                                }
                            }, 1000);//延时1s执行

                        }, 3000);
                        webView.loadUrl(js);
                    }
                }
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, String webUrl) {
                Log.d("web_url_test", webUrl);
                contentWebView.loadUrl(webUrl);
                return true;
            }


        });
        contentWebView.addJavascriptInterface(new Joymusic(), "joymusic");
        //那我再运行一下
    }

    /**
     * 正式环境所用
     */
    private void getUserInfo() {
        externalParamsMap = new HashMap<>();
        progress_img.setVisibility(View.VISIBLE);
        userMac = SetNetWorkUtils.getInstance(this).localMac();
        externalParamsMap.put("username", userMac);
//        externalParamsMap.put("userId", "test112");
        loginInfo();
        return;
    }

    private void loginInfo() {
        handler.sendEmptyMessage(MSG_LOAD_HOME_URL);
    }

    @Override
    public boolean onKeyDown(int keycode, KeyEvent keyEvent) {

        if (keycode == KeyEvent.KEYCODE_BACK) {
            Log.d(TAG, "KEYCODE_BACK");
            contentWebView.loadUrl("javascript:__return()");
            return true;
        }
        return super.onKeyDown(keycode, keyEvent);
    }


    private boolean isSimple = false;
    private String notifyUrl = null;

    private final class Joymusic {

        private Joymusic() {
        }
        @JavascriptInterface
        public void androidLog(String e){
            Log.e(TAG, "androidLog: "+e );
        }

        @JavascriptInterface
        public void exitApp(int num) {
            Log.d(TAG, "exitApp()");
            if (num == 2) {
                if (isExit) {
                    DeletePkgUtils.deleteAll(MainActivity.this);
                    finish();
                    System.exit(0);
                    return;
                }
                /**2020.3.6 修改toast方法*/
                ToastUtils.showShortToast("再按一次退出");
                isExit = true;
                handler.sendEmptyMessageDelayed(MSG_EXIT_DELAY, 2000L);
            } else {
                finish();
                System.exit(0);
                return;
            }
        }

        @JavascriptInterface
        public String getValues(String key) {
            String str = "";
            if (externalParamsMap != null) {
                if (externalParamsMap.containsKey(key))
                    str = externalParamsMap.get(key);
            }
            Log.e(TAG, "getValues: "+key+"_______"+str);
            return str;
        }

        @JavascriptInterface
        public void goneSplash() {
            runOnUiThread(() -> {
                if (progress_img.getVisibility() == View.VISIBLE) {
                    progress_img.setVisibility(View.GONE);
                }
            });
        }

        @JavascriptInterface
        public void startPlay(int position, String urlJsonArray, String weburl, String notifyUrl, boolean isCharge, boolean isSimple) {
            MainActivity.this.isSimple = isSimple;
            MainActivity.this.notifyUrl = notifyUrl;
            StringBuilder sb = new StringBuilder();
            sb.append("__position=" + position);
            sb.append("__urlArray=" + urlJsonArray);
            Log.d("playtest", sb.toString());
            startPosition = position;
            initPlayInfoList(urlJsonArray);
            String songpath = videoBeanList.get(startPosition).getSongRes();
           /* if (songpath.contains("Contentid")) {
                String path[] = songpath.split("&");
                for (int i = 0; i < path.length; i++) {
                    if (path[i].contains("Contentid")) {
                        contentId = path[i].substring(path[i].indexOf("=") + 1);
                    }
                }
            } else contentId = null;*/
            if (videoBeanList.size() > 0 && videoBeanList.size() > startPosition) {
                firstUrl = videoBeanList.get(startPosition).getCres();
//                if (isCharge) {
//                    NewAuth(videoBeanList.get(startPosition).getSongId());
//                } else
                handler.sendEmptyMessage(MSG_TO_PLAY_ACTIVITY);
            }
        }

        @JavascriptInterface
        public void closePop() {
            Log.d(TAG, "JAVA_JS");
            PlayUtils.getInstance().hideAudioLayout();
        }

        @JavascriptInterface
        public void audioMute(boolean isflag) {
            PlayUtils.getInstance().audioStop(MainActivity.this, isflag);
        }

        @JavascriptInterface
        public void startPop(String urlJsonArray, int width, int height, int x, int y) {
            /** 2020.11.26*/
            StringBuilder sb = new StringBuilder();
            sb.append("__urlJsonArray=" + urlJsonArray);
            Log.d("play_tests", sb.toString());
            initPlayInfoList(urlJsonArray);
            popStartPos = 0;
            if (videoBeanList.size() > 0 && videoBeanList.size() > popStartPos) {
                String id = videoBeanList.get(popStartPos).getSongRes();
                PlayUtils.getInstance().createAudioLayout(MainActivity.this, id, videoBeanList, width, height, x, y);
                PlayUtils.getInstance().showAudioLayout(MainActivity.this);

            }
        }
    }


    private void initPlayInfoList(String urlJson) {

        Type type = new TypeToken<List<VideoBean>>() {
        }.getType();
        videoBeanList = (new Gson().fromJson(urlJson, type));
    }

    private String contentId = "";


    private void NewAuth(String songId) {
    }

    private void NewPay(String songId) {
    }

    @Override
    public void JavaWebSocketOpen(WebSocketClient mJavaWebSocketClient) {
//        runOnUiThread(() -> {
//            ToastUtils.showShortToast("JavaSocket连接成功");
        Log.d(TAG, "JavaSocket连接成功");
//        });
    }

    @Override
    public void JavaWebsocketClosed(int code, String reason, boolean remote) {
        runOnUiThread(() -> {
//            ToastUtils.showShortToast("JavaSocket连接关闭");
            LiveDataBus.getInstance().send("webSLogin", true);
        });
        Log.d(TAG, "JavaSocket连接关闭");
    }

    @Override
    public void JavaWebSocketError(Exception ex) {
        runOnUiThread(() -> {
//            ToastUtils.showShortToast("连接失败");
            LiveDataBus.getInstance().send("webSLogin", true);
        });
        Log.d(TAG, "JavaSocket连接关闭");
    }

    @Override
    protected void onDestroy() {
        handler.removeCallbacksAndMessages(null);
        MyApp.getInstance().removeActivity(this);
        if (disposables != null) {
            if (disposables.size() > 0) {
                disposables.clear();
            }
        }
//        Intent intent = new Intent(MainActivity.this, MPushService.class);
//        stopService(intent);
        try {
            /**2019.4.23 替换为websocket*/
            if (WebScoketClient.getJavaWebSocket() != null)
                WebScoketClient.getJavaWebSocket().close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }
}